package com.ljf.game.handler;

import com.ljf.game.WebsocketManager;
import com.ljf.game.event.Event;
import com.ljf.game.event.EventManager;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述 :
 * <p>
 * 版本     作者     时间      内容
 * 1.0      lijinfeng       2025-04-17 10:08     create
 */
public class GameWebSocketHandler extends TextWebSocketHandler {

    // 监听：连接开启
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String username = session.getAttributes().get("username").toString();
        WebsocketManager.add(username,session);

    }

    // 监听：连接关闭
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status)  {
        String username = session.getAttributes().get("username").toString();
        System.out.println("连接断开，用户【"+username+"】");
        WebsocketManager.remove(username);

    }

    // 收到消息
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 分析message,转化为事件，执行对应的事件方法
        String jsonMessage = message.getPayload();
        Event event = Event.toEvent(jsonMessage,Event.class);
        EventManager.handlerEvent(session,event);
    }
}
